package com.bkhech.home.practice.spring.el.bean_ref;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.expression.BeanFactoryResolver;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.util.Arrays;

/**
 * EL bean 引用
 * <p>
 * 1. If the evaluation context has been configured with a bean resolver,
 * you can look up beans from an expression by using the @ symbol.
 * 2. To access a factory bean itself, you should instead prefix the bean name with an & symbol.
 * @author guowm
 * @date 2023/1/16
 */
public class ElBeanReferencesDemo {

    public static void main(String[] args) {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
        SpringBeanFactoryBean springBeanFactoryBean = applicationContext.getBean("springBeanFactoryBean", SpringBeanFactoryBean.class);
        System.out.println(springBeanFactoryBean);

        ExpressionParser parser = new SpelExpressionParser();

        StandardEvaluationContext evaluationContext = new StandardEvaluationContext();
        // BeanFactoryResolver 官方提供的一个基于 BeanFactory 的默认实现
        evaluationContext.setBeanResolver(new BeanFactoryResolver(springBeanFactoryBean.getBeanFactory()));

        // look up beans
        // This will end up calling resolve(context,"elBeanReference") on MyBeanResolver during evaluation
        Object elBeanReference = parser.parseExpression("@elBeanReference").getValue(evaluationContext);
        System.out.println(elBeanReference);

        // To access a factory bean itself. you should instead prefix the bean name with an & symbol


    }
}
